import {
  getVideoList
} from "../../../api/common";
const app = getApp()
const _api = require('../../../utils/api.js');
const apiurl = require('../../../utils/apiurl/public.js');
Page({
  data: {
    currSwiperIdx: 0,
    getuser: {},
    showModal: false,
    showPay: false,
    code: '',
    ablumData: [],
    cflist: [],
    botindex: 0,
    isfav: 0,
    videoId: '',
    windowHeight: 0,
    ispayd: 0, //禁止播放
    imgArr: [],
    showMediaPosterBg: false,
    playbtn: false, //是否显示播放、暂停、重播按钮，不包括视频封面的播放按钮。
    currIdx: 0,
    isLoadFinish: true,
    urlArray: [],
    showVideoImgBg: false, // 是否显示背景
    lastVideoContext: undefined, // 上一个video上下文
    currentVideoContext: undefined, // 当前video上下文
    nextVideoContext: undefined, // 下一个video上下文
    videoPause: false, // 控制视频显示隐藏
    windowWidth: 0,
    needChangeVideo: false, // 需要选集
    isFullScreen: false, // 是否全屏
    needVideoLoading: true, // 需要加载态
    duration:500,
    product:[]
  },
  async onLoad(option) {
    const {
      ablum_id,
      episodes_id,
      id,
      num,
      link_id,
      aid,
      channel_id
    } = option;
  
    let video_id = ablum_id ? ablum_id : id
    let sid = episodes_id ? episodes_id : num
   
    if (channel_id) {
      tt.setStorageSync('channelid', channel_id)
    }
    if (link_id) {
      tt.setStorageSync('linkid' + video_id, link_id)
      tt.setStorageSync('linkid', link_id)
    } else {
      if (tt.getStorageSync('linkid' + video_id)) {
        tt.setStorageSync('linkid', tt.getStorageSync('linkid' + video_id))
      } else {
        tt.setStorageSync('linkid', 0)
      }
    }
    let code = await _api.ttlogin();
    // 获取窗口高度
    const {
      windowHeight,
      windowWidth
    } = app.globalData?.systemInfo;
  
    this.setData({
      windowHeight,
      code,
      videoId: video_id,
      getuser: tt.getStorageSync('getuser'),
      windowWidth: Number(windowWidth),
    });
    await this.formatVideoData(video_id, sid);
    tt.disableUserScreenRecord()
  },
  onShow() {
    tt.disableUserScreenRecord()
  },
  onHide() {
    tt.enableUserScreenRecord()
  },
  onReady: function () {
    this.currentVideoContext = tt.createVideoContext(0 + "");
    this.currentVideoContext.play();
    const res = tt.canIPutStuffOverComponent('video');
   
  },
  swiperChange: function (e) {
    const lastId = this.data.currIdx;

    let next = this.data.ablumData[e.detail.current].ispayd

    this.setData({
      currSwiperIdx: e.detail.current,
      currIdx: e.detail.current,
      videoPause: false,
      videoError: false,
      needVideoLoading: true,
      ispayd: next,
      duration:500
    });
    const currentId = this.data.currIdx;

    this.lastVideoContext = tt.createVideoContext(lastId + "");
    this.currentVideoContext = tt.createVideoContext(currentId + "");
    this.lastVideoContext.pause();
    if (next) {
      this.currentVideoContext.pause();
      this.currentVideoContext.stop();
      this.getChapterdetail(e.detail.current)
    } else {
      setTimeout(() => {
        this.currentVideoContext.play();
      }, 300);
    }
  },
  ended(e){
  
    let es={
      'detail':{
      'current':this.data.currSwiperIdx+1
    }
    }
    this.swiperChange(es)
  },
  start(e) {
    // TODO: 实现逻辑
  },
  // 控制视频播放&暂停
  videoPlay(e) {
   
    const {
      videoPause
    } = e.detail;
    this.currentVideoContext[videoPause ? 'play' : 'pause']();
  },
  move: function () {},
  // 退出全屏
  exitFullscreen(e) {
    const {
      videoCurrentTimeSec
    } = e.detail
  
    this.setData({
      isFullScreen: false,
      isExitFullscreen: true,
    })
    this.currentVideoContext.exitFullScreen();
  },
  // 全屏控制视频播放与暂停
  fullScreenVideoPause(e) {
  
    const {
      isVideoPlay
    } = e.detail;
    this.currentVideoContext[isVideoPlay ? 'pause' : 'play']();
  },
  videoSeekHandler() {
    console.log('videoSeekHandler');
  },
  end: function () {
   
    // TODO: 实现逻辑
  },
  playerPlay: function () {
   
    // TODO: 实现逻辑
  },
  error(e) {
    tt.showToast({
      title: `${e.detail.errMsg}`,
      icon: "none",
    });
  
    this.setData({
      videoError: true,
      needVideoLoading: false,
    })
  },
  fullScreenChangeVideo() {

    this.setData({
      needChangeVideo: true,
    })
  },
  // 首次加载
  async formatVideoData(aid, eid) {
    // 如果携带剧集id进来的话，需要计算他属于那个pageSize,
    const {
      data,
      info
    } = await getVideoList(aid, eid);
    let chapnum = Number(eid) || 1;
    info.episodes = data;
    const currentAblum = info;
    const currentItem = data;
    const urlArray = currentItem.map(i => i.video_url);
    const videoCurrentIndex = currentItem.findIndex(i => i.chapnum === Number(eid)) || 0;
    const imgArr = currentItem.map(i => i.vertical_cover);
    let zfdata = this.splitArray(currentItem, 9) //拆分数组
    tt.setNavigationBarTitle({
      title: `${currentAblum.title}`,
    });
    if (urlArray.length < eid) {
      let Array = [];
      for (var i = 0; i < 15; i++) {
        Array.push('');
      }
      this.setData({
        urlArray: Array,
        imgArr: Array,
      });

      return false;
    }
   
    this.setData({
      urlArray: urlArray,
      imgArr: imgArr,
      ablumData: currentItem,
      currSwiperIdx: videoCurrentIndex,
      currentAblum,
      currIdx: videoCurrentIndex,
      ispayd: currentItem[videoCurrentIndex].ispayd,
      cflist: zfdata,
      product:currentAblum.data.data
    });
    if (!currentItem[videoCurrentIndex].ispayd) {
      this.JumpPlay(videoCurrentIndex)
    }
  },
  openPay() { //打开充值框
    this.setData({
      showPay: true
    })
  },
  hidePay() { //关闭充值框
    this.setData({
      showPay: false
    })
  },
  changeBot(e) { //切换底部的剧集分组

   
    this.setData({
      botindex: e.currentTarget.dataset.index
    })
  },
  checkPay(e){//选择充值的项
    let id=e.currentTarget.dataset.id
    let _this=this
  
    _api.post(apiurl.ordercreate,{id:id,clickid:_this.data.clickid}).then(res=>{
        if(res.data.code==0){
          let data=res.data;
      
          tt.pay({
            orderInfo: {
              order_id:data.data.order_id,
              order_token:data.data.order_token,
            },
            service: 5,
            _debug:1,
            success(res) {
              if (res.code == 0) {
                // 支付成功处理逻辑，只有res.code=0时，才表示支付成功
                // 但是最终状态要以商户后端结果为准
                console.log(res);
                console.log("成功");
                _this.setData({
                    showPay:false
                })
                _this.hideModal()
                _this.getProduct()
                console.log(_this.data.myindex)
                console.log(_this.data.current_index)
                // _this.getChapterdetail(_this.data.myindex)
                _this.getChapterdetail(_this.data.current_index)
                _this.getUserinfo()
              }
            },
            fail(res) {
              // 调起收银台失败处理逻辑
            },
          });
         
        }else if(res.data.code==103 || res.data.code==101){
          _this.logincode()
          setTimeout(()=>{
            _this.getCode()
          },1000)
         
        }
    })
},
  gotoPlay(e) {
    let currIdx = e.currentTarget.dataset.playnum - 1
   

  
    this.setData({
      duration:1
    })

    this.getChapterdetail(currIdx)
   
   
    // let _this = this
    // _api.get(apiurl.chapterinfo, {
    //   video_id: this.data.videoId,
    //   chapnum: this.data.ablumData[currIdx].chapnum
    // }).then(res => {

    //   if (res.data.virtual_currency) {
    //     _this.setData({
    //       'getuser.virtual_currency': res.data.virtual_currency,
    //     })
    //   }
    // })
    console.log(e)
  },
  hideModal(){//关闭选集
    this.setData({showModal:false})
  },
  getChapterdetail(currIdx){//获取某一集的信息
    console.log('this.getuser',this.data.getuser);
   
    var _this=this
    if(!this.data.getuser){
      this.getCode()
    }
    tt.showLoading({
        title: '数据加载中',
    })
   
    let findobj=this.data.ablumData[currIdx]
    if(findobj){
        _api.get(apiurl.chapterinfo,{video_id:this.data.videoId,chapnum:findobj.chapnum}).then(async res=>{
        
          console.log('res----',res);
            tt.hideLoading() 
            if(res.data.code==0){//如果正常播放
              this.setData({
                currIdx: currIdx,
                currSwiperIdx: currIdx,
                showModal: false,
                ispayd:false
              })
              this.data.ispayd=0
           
              setTimeout(()=>{

                _this.setData({
                  ispayd:0,
                  duration:500
                },500)
              })
              this.JumpPlay(currIdx) 
            }else if(res.data.code==103){//如果没有登录
              tt.setStorageSync('getuser', '')
              this.setData({
                'getuser':''
               })
             // let code = await _api.ttlogin();
             tt.showToast({
              title: res.data.msg+'请重新选集',
              icon:'none',
              duration: 3000
            });
              this.hideModal()
               
            }else if(res.data.code==105){//如果k币不足
                console.log(45454,res.data.virtual_currency)
               
                this.setData({
                  'getuser.virtual_currency':res.data.virtual_currency
                 })
               
                this.openPay()
            }
        })
    }
    
    
},
  splitArray(array, size) {
    let data = [];
    for (let i = 0; i < array.length; i += size) {
      data.push(array.slice(i, i + size))
    }
    return data
  },
  JumpPlay(videoCurrentIndex) {

    if (videoCurrentIndex != 0) {

      this.lastVideoContext = tt.createVideoContext(videoCurrentIndex - 1 + "");
      this.lastVideoContext.pause();
    }
    this.currentVideoContext = tt.createVideoContext(videoCurrentIndex + "");
    setTimeout(() => {
      this.currentVideoContext.play();
    }, 300);

  },
  async addAfter() {


    if (!tt.getStorageSync('getuser')) {
      this.getCode()
      return false;
    }else{
      this.setData({
        getuser: tt.getStorageSync('getuser')
      })
    }
    _api.post(apiurl.addfavorite, {
      video_id: this.data.videoId
    }).then(res => {
      console.log('加入成功', res)
      if (res.data.code == 0) {
        tt.showToast({
          title: '加入成功！',
        })
        setTimeout(() => {
          tt.hideToast()
          this.setData({
            isfav: 1
          })
        }, 1000)
      } else {
        if (res.data.msg == '请勿重复追剧') {
          setTimeout(() => {
            tt.hideToast()
            this.setData({
              isfav: 1
            })
          }, 1000)
        }
      }
    })
  },
  openTopup() { //打开选集

    if (!tt.getStorageSync('getuser')) {
      this.getCode()
      return false;
    }else{
      this.setData({
        getuser: tt.getStorageSync('getuser')
      })
    }
    console.log('data', this.data.getuser)
    this.setData({
      showModal: true
    })
  },
  async getCode() {

    console.log('this.data.code',this.data.code)
    if (this.data.code) {
      tt.getUserProfile({
        success: async ures => {


          let objdata = {
            'js_code': this.data.code,
            'encryptedData': ures.encryptedData,
            'iv': ures.iv,
            'type': 'tt'
          };
          _api.post(apiurl.login, objdata).then(async loginres => {

            if(loginres.code){
             let code = await _api.ttlogin();
             this.setData({
              code: code
            })
            }
            tt.setStorageSync('token', loginres.data.data.token)
            let userinfo = await _api.getUserinfo()
            this.setData({
              getuser: userinfo
            })
            console.log(userinfo)
          })

        },
        fail: err => {
          console.log(err)

        }
      })
    }


  },
  getUserinfo() {

  },
  // 根据索引求出当前这个视频在那一页
  getPageNoByIndex(data, index, pageSize) {
    const pageNo = Math.ceil((index + 1) / pageSize);
    return pageNo;
  },
  // 分页
  paginate(data, pageNo, pageSize) {
    const startIndex = (pageNo - 1) * pageSize;
    const endIndex = startIndex + pageSize;
    const pageData = data.slice(startIndex, endIndex);
    return pageData
  },
  timeUpdateHandler(e) {
    const {
      once
    } = this.data
    const {
      currentTime,
      duration
    } = e.detail;
    if (!once) {
      this.setData({
        videoDuration: duration,
        once: true,
      })
    }
    this.setData({
      videoCurrentTime: currentTime,
    })
  },
  slideStart(e) {
    this.setData({
      isSlideStart: true,
    })
  },
  loadedmetadataHandler() {
    this.setData({
      needVideoLoading: false,
    })
  },
  slideEnd(e) {
    const {
      videoCurrentTimeSec
    } = e.detail;
    this.currentVideoContext.seek(videoCurrentTimeSec)
    this.setData({
      isSlideStart: false,
    })
  },
  customSliderHandler(ref) {
    this.customSliderRef = ref;
  },
  changeVideoDialogHandler(ref) {
    this.changeVideoDialogRef = ref;
  },
  fullScreenSlideEnd(e) {
    console.log("fullScreenSlideEnd", e);
    const {
      videoCurrentTimeSec
    } = e.detail;
    this.currentVideoContext.seek(videoCurrentTimeSec)

  },
  changeVideo() {
    this.setData({
      needChangeVideo: true,
    })
  },
  cancelChangeVideo() {
    this.setData({
      needChangeVideo: false,
    })
  },
  changeFullScreen() {
    this.setData({
      isFullScreen: true,
    })
    this.currentVideoContext.play()
    setTimeout(() => {
      this.currentVideoContext.requestFullScreen();
    }, 100);
  },
  fullScreenToolHandler(ref) {
    this.fullScreenToolRef = ref;
  },
  onTapVideo(e) {
    const {
      isFullScreen
    } = this.data;
    console.log(e, this.fullScreenToolRef, isFullScreen);
    if (isFullScreen) {
      this.setData({
        toolAppear: true
      })
      // this.fullScreenToolRef.toolAppear();
    }
  }
})